#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include "user_auth.h"
#include "common.h"

void register_user(int socket_fd) {
    send(socket_fd, "REGISTER", 8, 0);

    char account[ACCOUNT_LENGTH + 1];
    if (recv(socket_fd, account, sizeof(account), 0) <= 0) {
        perror("接收账号失败");
        return;
    }

    char name[30] = {0};
    char password[30] = {0};

    printf("请输入用户名: ");
    fgets(name, sizeof(name), stdin);
    name[strcspn(name, "\n")] = '\0';

    printf("请输入密码: ");
    fgets(password, sizeof(password), stdin);
    password[strcspn(password, "\n")] = '\0';

    struct account_info reg_info;
    memset(&reg_info, 0, sizeof(reg_info));
    strncpy(reg_info.a, account, ACCOUNT_LENGTH);
    strncpy(reg_info.user_name, name, sizeof(reg_info.user_name) - 1);
    strncpy(reg_info.password, password, sizeof(reg_info.password) - 1);

    if (send(socket_fd, &reg_info, sizeof(reg_info), 0) < 0) {
        perror("发送注册信息失败");
    }

    char response[1024];
    if (recv(socket_fd, response, sizeof(response), 0) > 0) {
        printf("\n%s\n", response);
    }
}

int login_user(int socket_fd) {
    struct login_info login_data;
    memset(&login_data, 0, sizeof(login_data));

    if (send(socket_fd, "LOGIN", 5, 0) < 0) {
        perror("发送登录请求失败");
        return -1;
    }

    printf("请输入用户名或账号: ");
    fgets(login_data.identifier, sizeof(login_data.identifier), stdin);
    login_data.identifier[strcspn(login_data.identifier, "\n")] = '\0';

    printf("请输入密码: ");
    fgets(login_data.password, sizeof(login_data.password), stdin);
    login_data.password[strcspn(login_data.password, "\n")] = '\0';

    if (send(socket_fd, &login_data, sizeof(login_data), 0) < 0) {
        perror("发送登录信息失败");
        return -1;
    }

    char response[1024];
    int ret = recv(socket_fd, response, sizeof(response), 0);
    if (ret > 0) {
        response[ret] = '\0';
        printf("\n%s\n", response);

        if (strstr(response, "LOGIN_SUCCESS") != NULL) {
            printf("登录成功，开始聊天...\n");
            return 0;
        }
    }

    return 1;
}